package com.jintu.portal.service.impl;

import com.jintu.portal.pojo.bean.Filter;
import com.jintu.portal.pojo.bean.IsAdmin;
import com.jintu.portal.pojo.bean.QLBuilder;
import com.jintu.portal.pojo.bean.SystemType;
import com.jintu.portal.pojo.dto.IndexInfoDto;
import com.jintu.portal.pojo.dto.MenuDto;
import com.jintu.portal.pojo.dto.PullAreaDto;
import com.jintu.portal.pojo.dto.TobUserDto;
import com.jintu.portal.pojo.entity.ExtendCode;
import com.jintu.portal.pojo.entity.Menu;
import com.jintu.portal.pojo.entity.TMenu;
import com.jintu.portal.pojo.entity.UserCodeRel;
import com.jintu.portal.repository.mysql.dao.ExtendCodeDao;
import com.jintu.portal.repository.mysql.dao.MenuDao;
import com.jintu.portal.repository.mysql.dao.UserCodeRelDao;
import com.jintu.portal.service.IndexService;
import com.jintu.portal.utils.BeanUtils;
import com.jintu.portal.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liyou on 2017/9/29.
 */
@Slf4j
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private ExtendCodeDao extendCodeDao;

    @Autowired
    private UserCodeRelDao userCodeRelDao;

//    @Autowired
//    private SysNoticeDao sysNoticeDao;
//
//    @Autowired
//    private CompanyNoticeDao companyNoticeDao;
//
//    @Autowired
//    private SysMsgDao sysMsgDao;
//
//    @Autowired
//    private VersionDao versionDao;
//
//    @Autowired
//    private StagingService stagingService;
//
//    @Autowired
//    private CommonService commonService;
//
//    @Autowired
//    private ScreensaverService screensaverService;
//
//    @Autowired
//    private UserDao userDao;

    public IndexInfoDto indexInfo(HttpServletRequest request) throws Exception {
        String token = request.getParameter("token");
        Long userId = UserUtil.tobCurrentUser1(token).getUserId();

        log.info("当前用户：" + userId);
        IndexInfoDto indexInfoDto = new IndexInfoDto();
        List<Menu> menuNewList = new ArrayList<>();
        QLBuilder ql = new QLBuilder();
        ql.add("order by sort");
        List<Menu> menuList = menuDao.findManyByJpql(ql);
        for(Menu menu : menuList){
            menuNewList.add(menu);
        }
        List<MenuDto> menuListRs = BeanUtils.copyProperties(menuNewList, MenuDto.class);

        QLBuilder ql1 = new QLBuilder();
        ql1.setMainClause("select DISTINCT(type) from ExtendCode where areaId is not null");
        List<ExtendCode> typeList = extendCodeDao.findManyByJpql(ql1);

        for(MenuDto dto : menuListRs){
            dto.setIsBind(0);
            if(typeList.contains(dto.getId())){
                List<Object> paramList = new ArrayList<Object>();
                String areaSql="select DISTINCT area_id as areaId,area_name as areaName from extend_code where type = :type";
                paramList.add(dto.getId());
                List<ExtendCode> areaList = extendCodeDao.findManyBySql(areaSql,ExtendCode.class,paramList);
                dto.setAreaList(areaList);
            }
            QLBuilder qlRel = new QLBuilder();
            qlRel.and(Filter.eq("userId", userId));
            qlRel.and(Filter.eq("type", dto.getId()));
            UserCodeRel userCodeRel = userCodeRelDao.findOneByJpql(qlRel);
            if(userCodeRel != null){
                dto.setIsBind(1);
            }
        }

        indexInfoDto.setMenuList(menuListRs);

//        ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.tob.dto.NoticeListDto(tsn.id, tsn.startTime, tsn.title, tsn.imgUrl, 1) FROM TSysNotice tsn, TSysNoticeCompany tsc WHERE tsn.id = tsc.sysNoticeId");
//        ql.and(Filter.eq("tsc.companyId", tobUserDto.getCompanyId()));
//        ql.and(Filter.like("tsn.showChannel", "%"+ShowChannel.B_APP.getValue()+"%"));
//        ql.and(Filter.le("tsn.startTime", new Date()));
//        ql.and(Filter.gt("tsn.appEndTime", new Date()));
//        ql.and(Filter.isNull("tsn.status"));
//        ql.and(Filter.eq("tsn.logicDelete",LogicDelete.NOT_DELETE.getValue()));
//        ql.add("order by tsn.startTime desc");
//        List<NoticeListDto> sysNoticeList = sysNoticeDao.findManyByJpql(ql);
//        indexInfoDto.setSysNoticeList(sysNoticeList);

//        ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.tob.dto.NoticeListDto(tcn.id, tcn.startTime, tcn.title, tcn.imgUrl, 2) FROM TCompanyNotice tcn, TCompanyNoticeDepartment tcnd WHERE tcn.id = tcnd.companyNoticeId");
//        ql.and(Filter.eq("tcnd.departmentId", tobUserDto.getDepartmentId()));
//        ql.and(Filter.le("tcn.startTime", new Date()));
//        ql.and(Filter.gt("tcn.endTime", new Date()));
//        ql.and(Filter.isNull("tcn.status"));
//        ql.and(Filter.eq("tcn.logicDelete",LogicDelete.NOT_DELETE.getValue()));
//        ql.add("order by tcn.startTime desc");
//        List<NoticeListDto> companyNoticeList = companyNoticeDao.findManyByJpql(ql);
//        indexInfoDto.setCompanyNoticeList(companyNoticeList);
//        //首页消息红点控制 只返回一条数据红点不显示，大于一条红点显示
//        ql = new QLBuilder();
//        ql.and(Filter.eq("channel", MsgChannel.B_APP.getValue()));
//        ql.and(Filter.eq("showType", MsgShowType.SHOW.getValue()));
//        ql.and(Filter.eq("receiveId", tobUserDto.getUserId()));
//        ql.and(Filter.eq("departmentId", tobUserDto.getDepartmentId()));
//        ql.and(Filter.eq("status", IsView.VIEW_NO.getValue()));
//        List<TSysMsg> msgList = sysMsgDao.findManyByJpql(ql);
//        indexInfoDto.setIsView(IsView.VIEW_YES.getValue());
//        if(!CollectionUtils.isEmpty(msgList) && msgList.size()>1){
//            indexInfoDto.setIsView(IsView.VIEW_NO.getValue());
//        }
        //返回最新的消息
//        ql = new QLBuilder();
//        ql.setMainClause("SELECT max(id) FROM TSysMsg t");
//        ql.and(Filter.eq("channel", MsgChannel.B_APP.getValue()));
//        ql.and(Filter.eq("showType", MsgShowType.SHOW.getValue()));
//        ql.and(Filter.eq("receiveId", tobUserDto.getUserId()));
//        ql.and(Filter.eq("departmentId", tobUserDto.getDepartmentId()));
//        Long msgId = sysMsgDao.findOneByJpql(ql);
//        if(msgId != null){
//            ql = new QLBuilder();
//            ql.setMainClause("SELECT new com.drip.tob.dto.SysMsgDto(t) FROM TSysMsg t");
//            ql.and(Filter.eq("id", msgId));
//            SysMsgDto sysMsgDto = sysMsgDao.findOneByJpql(ql);
//            MsgOrderDto msgOrderDto = JsonUtil.fromJson(sysMsgDto.getExtendParams(), MsgOrderDto.class);
//            if(MsgServiceType.BILL_NOTICE.getValue().equals(sysMsgDto.getServiceType())) {
//                sysMsgDto.setContent(msgOrderDto.getContent());
//                sysMsgDto.setMoney(msgOrderDto.getMoney());
//                sysMsgDto.setRelId(msgOrderDto.getOrderId().toString());
//                sysMsgDto.setServiceTypeText(msgOrderDto.getServiceTypeText());
//                sysMsgDto.setTypeText(msgOrderDto.getTypeText());
//            }
//            indexInfoDto.setSysMsgDto(sysMsgDto);
//        }
//        //ca默认系统公告
//        if(indexInfoDto.getSysMsgDto()==null){
//            List<TStaticData> dsnList = commonService.findDataByCode(StaticDataConstants.DEFAULT_SYS_NOTICE);
//            if(!CollectionUtils.isEmpty(dsnList) && StringUtil.isNotEmpty(dsnList.get(0).getVal())){
//                TSysNotice sysNotice = sysNoticeDao.get(Long.parseLong(dsnList.get(0).getVal()));
//                if(sysNotice != null){
//                    NoticeListDto caDefaultNotice = new NoticeListDto(sysNotice.getId(),sysNotice.getStartTime(),sysNotice.getTitle(),sysNotice.getImgUrl(),1);
//                    indexInfoDto.getSysNoticeList().add(0,caDefaultNotice);
//                }
//            }
//        }
        return indexInfoDto;
    }

//    public VersionDto checkUpdate(String appOs, String appName, String verson) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT max(appVersion), max(mustFlag) FROM TVersion");
//        ql.and(Filter.eq("appOs", appOs));
//        ql.and(Filter.eq("appName", appName));
//        ql.and(Filter.gt("appVersion", verson));
//        Object[] objs = versionDao.findOneByJpql(ql);
//        if(objs == null || objs[0] == null) {
//            return null;
//        }
//        String appVersion = objs[0].toString();
//        Integer mustFlag = Integer.parseInt(objs[1].toString());
//        if(StringUtil.isBlank(appVersion)) {
//            return null;
//        }
//        ql = new QLBuilder();
//        ql.and(Filter.eq("appOs", appOs));
//        ql.and(Filter.eq("appName", appName));
//        ql.and(Filter.eq("appVersion", appVersion));
//        TVersion version = versionDao.findOneByJpql(ql);
//        VersionDto versionDto = BeanUtils.copyProperties(version, VersionDto.class);
//        versionDto.setMustFlag(mustFlag);
//        return versionDto;
//    }
//
//    /**
//     * 校验当前APP用户是否有退款权限
//     * @return
//     * @throws Exception
//     */
//    public TMenu checkTobUserRefundRight() throws Exception{
//        TMenu rsDto = null;   //默认无
//
//        //当前登录用户
//        TobUserDto currUser = UserUtil.tobCurrentUser();
//
//        //tob-app可退款审核的版本号
//        List<TStaticData> staticDataList = commonService.findDataByCode(StaticDataConstants.REFUND_APP_VERSION);
//        String refundAppVersion = "";
//        if(staticDataList != null && staticDataList.size() > 0){
//            refundAppVersion = staticDataList.get(0).getVal();
//        }
//        if(StringUtil.isBlank(refundAppVersion)){
//            //版本号未配置,定然没有退款权限
//            return rsDto;
//        }
//        String currVersion = currUser.getVersion();
//        if(currVersion.compareTo(refundAppVersion) < 0){
//            //当前版本号小于配置中的值,定然没有退款权限
//            return rsDto;
//        }
//
//        //tob退款审核菜单
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("system", SystemType.B_APP_SYSTEM.getValue()));
//        ql.and(Filter.eq("type", 3));
//        TMenu refundMenu = menuDao.findOneByJpql(ql);
//        if(refundMenu == null){
//            //tob-app退款权限菜单未配置,定然没有退款权限
//            return rsDto;
//        }
//
//        //校验员工数据
//        TUser user = userDao.get(currUser.getUserId());   //实时取用户
//        if(user.getRefundRight() == null || user.getRefundRight().intValue() != 1){
//            //员工未配置退款权限
//            return rsDto;
//        }else{
//            rsDto = refundMenu;
//        }
//
//        return rsDto;
//    }
}
